'''
Created on 2010-10-11

@author: Chine
'''
import re, os, codecs
from django.utils.html import escape

_article_split = r"<p><!-- pagebreak --></p>"
get_article_abstract = lambda s: s.split(_article_split)[0]


_html_tags_regex = re.compile(r'<\/?[^>]*>', re.IGNORECASE)
_space_regex = re.compile(r'\s')
def split_html_tags(s, clear_space=True): 
    rs = _html_tags_regex.sub('', s)
    
    if clear_space:
        rs = _space_regex.sub('', rs)
        rs = rs.replace('&nbsp;', '')
        
    return rs

##
# Removes HTML markup from a text string.
#
# @param text The HTML source.
# @return The plain text.  If the HTML source contains non-ASCII
#     entities or character references, this is a Unicode string.

def strip_html(text):
    def fixup(m):
        text = m.group(0)
        if text[:1] == "<":
            return "" # ignore tags
        if text[:2] == "&#":
            try:
                if text[:3] == "&#x":
                    return unichr(int(text[3:-1], 16))
                else:
                    return unichr(int(text[2:-1]))
            except ValueError:
                pass
        elif text[:1] == "&":
            import htmlentitydefs
            entity = htmlentitydefs.entitydefs.get(text[1:-1])
            if entity:
                if entity[:2] == "&#":
                    try:
                        return unichr(int(entity[2:-1]))
                    except ValueError:
                        pass
                else:
                    return unicode(entity, "iso-8859-1")
        return text # leave as is
    return re.sub("(?s)<[^>]*>|&#?\w+;", fixup, text)

def add_weibo_name(basic_m_list):
    for m in basic_m_list:
        if m.avatar is not None and m.username.startswith('@'):
            m.weibo_name = m.username[1:]
        else:
            m.weibo_name = None
            
    return basic_m_list

def access_from_mobile(request):
    user_agent = request.META['HTTP_USER_AGENT']
    
    MOBILE_SPECIFIC_SUBSTRING = [
        "iPad","iPhone","Android","MIDP","Opera Mobi",   
        "Opera Mini","BlackBerry","HP iPAQ","IEMobile",   
        "MSIEMobile","Windows Phone","HTC","LG",   
        "MOT","Nokia","Symbian","Fennec",   
        "Maemo","Tear","Midori","armv",   
        "Windows CE","WindowsCE","Smartphone","240x320",   
        "176x220","320x320","160x160","webOS",   
        "Palm","Sagem","Samsung","SGH",   
        "SIE","SonyEricsson","MMP","UCWEB"]
    
    for mobile_str in MOBILE_SPECIFIC_SUBSTRING:
        if mobile_str in user_agent or mobile_str.lower() in user_agent \
            or mobile_str.upper() in user_agent:
            return True
        
    return False

process_newline = lambda content: escape(content).replace('\n', '<br />')

def render_str(template_name, args):
    args = tuple(args)
    
    rdr_file = codecs.open(template_name, 'r', 'utf-8')
    try:
        rdr_strs = rdr_file.read()
        return rdr_strs % args
    finally:
        rdr_file.close()
        
def render_mail_str(template_file_name, args):
    template_path = os.path.join(os.path.dirname(__file__), "templates", "blog", "mail", template_file_name)
    return render_str(template_path, args)